package pers.jing.android.helper.page

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import pers.jing.android.helper.AndroidSdkTools
import pers.jing.android.helper.ANDROID_SDK_PATH
import pers.jing.android.helper.DeviceManager
import pers.jing.android.helper.db.Database
import pers.jing.android.helper.model.CODE_SUCCESS
import pers.jing.android.helper.model.DeviceInfo
import pers.jing.android.helper.model.STATE_NONE
import pers.jing.android.helper.model.UIPage
import pers.jing.android.helper.model.UIDialogState

/**
 * 主页的ViewModel
 */
class MainViewModel(val database: Database,val deviceManager: DeviceManager): ViewModel() {

    private val _curPage = MutableStateFlow(UIPage("", ""))

    val curPage = _curPage.asStateFlow()

    private val _result = MutableStateFlow(UIDialogState(STATE_NONE))
    val result = _result.asStateFlow()

    init {
        loadDevices()
    }

    /**
     * 每次启动APP, 先杀死adb server, 然后再通过adb devices启动
     */
    fun killServer() {
        viewModelScope.launch(Dispatchers.IO) {
            val path = database.getConfig(ANDROID_SDK_PATH)
            if (path == null) {
                return@launch
            }
            val result = AndroidSdkTools.killServer(path)
            if (CODE_SUCCESS != result.code) {
                result.error?.let {
                    it.forEach { line -> println(line) }
                }
            }
        }
    }

    fun loadDevices() {
        viewModelScope.launch(Dispatchers.IO) {
            deviceManager.loadDevices()
        }
    }

    fun getStateFlowDevices(): StateFlow<List<DeviceInfo>> {
        return deviceManager.getStateFlowDevices()
    }

}